package com.fsd.admin.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.fsd.admin.model.*;
import com.fsd.admin.service.*;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;
import com.fsd.core.wechat.entity.message.resp.TemplateMessage;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.fsd.admin.dao.B_articleDao;
import com.fsd.admin.entity.A_LoginInfo;
import com.google.gson.Gson;

@Repository("b_articleServiceImpl")
public class B_articleServiceImpl extends MainServiceImpl<B_article, String> implements B_articleService{
    
    private static final Logger log = Logger.getLogger(B_articleServiceImpl.class);
    private static String depict = "文章：";
    
    @Resource(name = "b_articleDaoImpl")
	public void setBaseDao(B_articleDao b_articleDao) {
		super.setBaseDao(b_articleDao);
	}
	
	@Resource(name = "b_articleDaoImpl")
	private B_articleDao objectDao;

    @Resource(name = "b_articlerelateServiceImpl")
	private B_articlerelateService articleRelateService;
    
    //用户
    @Resource(name = "A_EmployeeServiceImpl")
	private A_EmployeeService employeeService;
    
    //系统参数
    @Resource(name = "Sys_SystemParametersServiceImpl")
	private Sys_SystemParametersService sysParamService;
    
    //微信推送模板
    @Resource(name = "e_pushtemplatesServiceImpl")
	private E_pushtemplatesService pushtemplatesService;

    @Resource(name = "b_downloadServiceImpl")
	private B_downloadService downloadService;

    @Resource(name = "b_wordkeybadServiceImpl")
	private B_wordkeybadService wordkeybadService;

    @Resource(name = "b_subjectServiceImpl")
	private B_subjectService subjectService;

	@Resource(name = "n_pushsettingsServiceImpl")
	private N_pushsettingsService pushsettingsService;
    
    //wzlx 文章类型
	/**
     * 文章
     */
	public static final String wzwz1 = "wzwz";
	public static final String wzwz2 = "文章";
	/**
     * 组图
     */
	public static final String wzzt1 = "wzzt";
	public static final String wzzt2 = "组图";
	/**
     * 视频
     */
	public static final String wzsp1 = "wzsp";
	public static final String wzsp2 = "视频";
	/**
     * 文件
     */
	public static final String wzwj1 = "wzwj";
	public static final String wzwj2 = "文件";
	/**
     * 领导
     */
	public static final String wzld1 = "wzld";
	public static final String wzld2 = "领导";
	/**
     * 公文
     */
	public static final String wzgw1 = "wzgw";
	public static final String wzgw2 = "公文";
	/**
     * 访谈
     */
	public static final String wzft1 = "wzft";
	public static final String wzft2 = "访谈";
	/**
     * Flash
     */
	public static final String wzdh1 = "wzdh";
	public static final String wzdh2 = "Flash";
    
    /**
     * 过滤文章标记内容
     * @param param
	 * @param type
     * @return
     * @throws Exception
     */
	public Object getArticleMContent(ParametersUtil param, String type) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		if(objectMap.get("content") != null && !"".equals(objectMap.get("content"))){
			String value = objectMap.get("content").toString();
			if (type.equals("coopyyb")){
				value = value.replaceAll("<img (.[^>]*)>", "");
				value = value.replaceAll("<IMG (.[^>]*)>", "");
			}else{
				value = value.replaceAll("<p>", "<P>");
				value = value.replaceAll("<p (.[^>]*)>", "<P>");
				value = value.replaceAll("<P (.[^>]*)>", "<P>");
				value = value.replaceAll("<[^P](.[^>]*)>", "");
				value = value.replaceAll("<P>", "<BR/>　　");
			}
			return value;
		}
		return "";
	}

	/**
	 * 加载文本文章分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getArticlePageList(ParametersUtil param, A_LoginInfo loginInfo) throws Exception{
		A_Employee employee = loginInfo.getEmployee();
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.desc("adddate"));
		if (!employee.isIsadmin()){
			List<String> menuIDs = loginInfo.getPopedomMap().get(Config.POPEDOMMEUN);
			if (menuIDs.indexOf(Config.POPEDOMjggly) != -1){//机构管理员
				List<String> branchIDs = loginInfo.getPopedomMap().get(Config.POPEDOMBRANCH);
				branchIDs.add(employee.getBranchid());
				c.add(Restrictions.in("branchid", branchIDs));
			}else{
				c.add(Restrictions.eq("addemployeeid", employee.getId()));
			}
		}
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("id") != null && !"".equals(objectMap.get("id"))){
				c.add(Restrictions.like("id", "%" + objectMap.get("id") + "%"));
			}
			if(objectMap.get("title") != null && !"".equals(objectMap.get("title"))){
				c.add(Restrictions.like("title", "%" + objectMap.get("title") + "%"));
			}
			if(objectMap.get("type") != null && !"".equals(objectMap.get("type"))){
				c.add(Restrictions.eq("type", objectMap.get("type")));
			}else{
				Disjunction disjunction = Restrictions.disjunction();
				disjunction.add(Restrictions.or(Restrictions.eq("type", wzwz1)));
				disjunction.add(Restrictions.or(Restrictions.eq("type", wzzt1)));
				disjunction.add(Restrictions.or(Restrictions.eq("type", wzsp1)));
				disjunction.add(Restrictions.or(Restrictions.eq("type", wzwj1)));
				disjunction.add(Restrictions.or(Restrictions.eq("type", wzdh1)));
				c.add(disjunction);
			}
			if(objectMap.get("subjectid") != null && !"".equals(objectMap.get("subjectid"))){
				c.add(Restrictions.eq("subjectid", objectMap.get("subjectid")));
			}
			if(objectMap.get("branchid") != null && !"".equals(objectMap.get("branchid"))){
				c.add(Restrictions.eq("branchid", objectMap.get("branchid")));
			}
			if(objectMap.get("showtype") != null && !"".equals(objectMap.get("showtype"))){
				c.add(Restrictions.eq("showtype", objectMap.get("showtype")));
			}
			if(objectMap.get("auditing") != null && !"".equals(objectMap.get("auditing"))){
				c.add(Restrictions.eq("auditing", objectMap.get("auditing")));
			}
			if(objectMap.get("firstly") != null && "true".equals(objectMap.get("firstly"))){
				c.add(Restrictions.eq("firstly", objectMap.get("firstly")));
			}
			if(objectMap.get("slide") != null && "true".equals(objectMap.get("slide"))){
				c.add(Restrictions.eq("slide", objectMap.get("slide")));
			}
			if(objectMap.get("ismobile") != null && "true".equals(objectMap.get("ismobile"))){
				c.add(Restrictions.eq("slide", objectMap.get("ismobile")));
			}
			if(objectMap.get("overdue") != null && !"".equals(objectMap.get("overdue"))){
				c.add(Restrictions.like("overdue", objectMap.get("overdue") + "%"));
			}
			if(objectMap.get("author") != null && !"".equals(objectMap.get("author"))){
				c.add(Restrictions.like("author", "%" + objectMap.get("author") + "%"));
			}
			if(objectMap.get("source") != null && !"".equals(objectMap.get("source"))){
				c.add(Restrictions.like("source", "%" + objectMap.get("source") + "%"));
			}
		}
		return objectDao.findPager(param, c);
	}
	
	/**
	 * 加载已删除文章分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getRecycleArticlePageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "1"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.desc("adddate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("title") != null && !"".equals(objectMap.get("title"))){
				c.add(Restrictions.like("title", "%" + objectMap.get("title") + "%"));
			}
		}
		return objectDao.findPager(param, c);
	}
	
	/**
	 * 保存文本文章
	 * @param obj
	 * @param param
	 * @param employee
	 * @throws Exception
	 */
	public ParametersUtil saveArticle(B_article obj, ParametersUtil param, A_Employee employee) throws Exception{
		//内容检查敏感词，待验收后实现
//		List<B_wordkeybad> list = this.wordkeybadService.getWordkeybadListByType(Config.WORDTYPEBAD, employee);
//		if (list != null && list.size() > 0){
//			String titleMsg = "";
//			String showMsg = "";
//			String abstractsMsg = "";
//			String contentMsg = "";
//			for (B_wordkeybad word : list) {
//				if (obj.getTitle().indexOf(word.getName()) > 0){
//					if (!titleMsg.equals("")){
//						titleMsg += "，";
//					}
//					titleMsg += word.getName();
//				}
//				if (obj.getShowtitle().indexOf(word.getName()) > 0){
//					if (!showMsg.equals("")){
//						showMsg += "，";
//					}
//					showMsg += word.getName();
//				}
//				if (obj.getAbstracts().indexOf(word.getName()) > 0){
//					if (!abstractsMsg.equals("")){
//						abstractsMsg += "，";
//					}
//					abstractsMsg += word.getName();
//				}
//				if (obj.getContent().indexOf(word.getName()) > 0){
//					if (!contentMsg.equals("")){
//						contentMsg += "，";
//					}
//					contentMsg += word.getName();
//				}
//			}
//			throw new BusinessException(describe + "中包含敏感词信息，检测词是：" + obj.getName());
//		}
		if(obj.getSubjectid() != null && !obj.getSubjectid().equals("")){
			B_subject sub = subjectService.get(obj.getSubjectid());
			if(sub != null){
				if(sub.getIspublish() != null && sub.getIspublish().equals("true") && sub.getDeleted().equals("0")){
					throw new BusinessException(depict + "栏目设置禁止发布，该栏目下禁止发布文章！");
				}
			}
		}
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			B_article obj_old = objectDao.get(obj.getId());
			obj_old.setSubjectid(obj.getSubjectid());
			obj_old.setSubjectname(obj.getSubjectname());
			obj_old.setShowtype(obj.getShowtype());
			obj_old.setShowtypename(obj.getShowtypename());
			obj_old.setTitle(obj.getTitle());
			obj_old.setSubtitle(obj.getSubtitle());
			obj_old.setShowtitle(obj.getShowtitle());
			obj_old.setTitlecolor(obj.getTitlecolor());
			obj_old.setKeyword(obj.getKeyword());
			obj_old.setIsaurl(obj.getIsaurl());
			obj_old.setAurl(obj.getAurl());
			obj_old.setAuthor(obj.getAuthor());
			obj_old.setSource(obj.getSource());
			obj_old.setImageurl1(obj.getImageurl1());
			obj_old.setImageurl2(obj.getImageurl2());
			obj_old.setVideourl(obj.getVideourl());
			obj_old.setVoiceurl(obj.getVoiceurl());
			obj_old.setAbstracts(obj.getAbstracts());
			obj_old.setContent(obj.getContent());
			obj_old.setOverdue(obj.getOverdue());
//					obj_old.setRecommend(obj.getRecommend());
//					obj_old.setVideo(obj.getVideo());
//					obj_old.setRoll(obj.getRoll());
//					obj_old.setHeadline(obj.getHeadline());
//					obj_old.setHot(obj.getHot());
//					obj_old.setComments(obj.getComments());
			obj_old.setRemark(obj.getRemark());
			obj_old.setBranchid(obj.getBranchid());
			obj_old.setBranchname(obj.getBranchname());
			obj_old.setAuditing("false");//标记未审批
			obj_old.setUpdatedate(this.getData());
			obj_old.setUpdateemployeeid(employee.getId());
			obj_old.setUpdateemployeename(employee.getRealname());
			if (obj.getAdddate() != null && !obj.getAdddate().equals("")
					&& obj.getAdddate().length() == 14){
				obj_old.setAdddate(obj.getAdddate());
			}
//					if (!"true".equals(obj.getFirstly())){
//						obj_old.setFirstly("false");
//					}
//					if (!"true".equals(obj.getSlide())){
//						obj_old.setSlide("false");
//					}
			objectDao.update(obj_old);
		}else{
			//添加
			String id = this.getUUID();
			obj.setId(id);
			obj.setCompanyid(employee.getCompanyid());
			obj.setAuditing("false");//标记未审批
			obj.setAddemployeeid(employee.getId());
			obj.setAddemployeename(employee.getRealname());
			obj.setDeleted("0");//0标识未删除
			if (obj.getAdddate() == null || obj.getAdddate().length() != 14)
				obj.setAdddate(this.getData());
			if (!"true".equals(obj.getFirstly())){
				obj.setFirstly("false");
			}
			if (!"true".equals(obj.getSlide())){
				obj.setSlide("false");
			}
			objectDao.save(obj);
		}

		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			articleRelateService.delObject(obj.getId(), Config.ARTICLERELATESUBJECT);
			articleRelateService.delObject(obj.getId(), Config.ARTICLERELATESUBJECTXG);
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			ArrayList<String> sidList = (ArrayList<String>) objectMap.get(Config.ARTICLERELATESUBJECT);
			ArrayList<String> sxgidList = (ArrayList<String>) objectMap.get(Config.ARTICLERELATESUBJECTXG);
			if (sidList.size() > 0){
				for (String id : sidList) {
					articleRelateService.saveArticleRelate(obj.getId(), id, Config.ARTICLERELATESUBJECT);
				}
			}
			if (sxgidList.size() > 0){
				for (String id : sxgidList) {
					articleRelateService.saveArticleRelate(obj.getId(), id, Config.ARTICLERELATESUBJECTXG);
				}
			}
		}
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getTitle(), employee, B_articleServiceImpl.class);
		ParametersUtil util = new ParametersUtil();
		util.addSendObject("id", obj.getId());
		return util;
	}
	
	/**
	 * 保存文本文章
	 * @param obj
	 * @param param
	 * @param employee
	 * @throws Exception
	 */
	public void saveArticleWap(B_article obj, ParametersUtil param, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			B_article obj_old = objectDao.get(obj.getId());
			obj_old.setIsmobile(obj.getIsmobile());
			obj_old.setMsubjectid(obj.getMsubjectid());
			obj_old.setMsubjectname(obj.getMsubjectname());
			obj_old.setMisaurl(obj.getMisaurl());
			obj_old.setMaurl(obj.getMaurl());
			obj_old.setMimageurl(obj.getMimageurl());
			obj_old.setMimagedepict(obj.getMimagedepict());
			obj_old.setMabstracts(obj.getMabstracts());
			obj_old.setMcontent(obj.getMcontent());
			obj_old.setAuditing("false");//标记未审批
			obj_old.setUpdatedate(this.getData());
			obj_old.setUpdateemployeeid(employee.getId());
			obj_old.setUpdateemployeename(employee.getRealname());
			objectDao.update(obj_old);
			
			if(param.getJsonData() != null && !"".equals(param.getJsonData())){
				articleRelateService.delObject(obj.getId(), Config.ARTICLERELATESUBJECTWAP);
				articleRelateService.delObject(obj.getId(), Config.ARTICLERELATESUBJECTWAPXG);
				Gson gs = new Gson();
				Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
				ArrayList<String> swapidList = (ArrayList<String>) objectMap.get(Config.ARTICLERELATESUBJECTWAP);
				ArrayList<String> swapxgidList = (ArrayList<String>) objectMap.get(Config.ARTICLERELATESUBJECTWAPXG);
				if (swapidList.size() > 0){
					for (String id : swapidList) {
						articleRelateService.saveArticleRelate(obj.getId(), id, Config.ARTICLERELATESUBJECTWAP);
					}
				}
				if (swapxgidList.size() > 0){
					for (String id : swapxgidList) {
						articleRelateService.saveArticleRelate(obj.getId(), id, Config.ARTICLERELATESUBJECTWAPXG);
					}
				}
			}
			this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + "移动版" + obj.getId() + obj.getTitle(), employee, B_articleServiceImpl.class);
		}else
			throw new BusinessException(depict + "内容信息不存在!");
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getArticleById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		B_article obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		ParametersUtil util = new ParametersUtil();
		util.addSendObject("data", obj);
		util.addSendObject(Config.ARTICLERELATESUBJECT, 
				articleRelateService.getObjectIDList(obj.getId(), Config.ARTICLERELATESUBJECT));
		util.addSendObject(Config.ARTICLERELATESUBJECTXG, 
				articleRelateService.getObjectIDList(obj.getId(), Config.ARTICLERELATESUBJECTXG));
		util.addSendObject(Config.ARTICLERELATESUBJECTWAP, 
				articleRelateService.getObjectIDList(obj.getId(), Config.ARTICLERELATESUBJECTWAP));
		util.addSendObject(Config.ARTICLERELATESUBJECTWAPXG, 
				articleRelateService.getObjectIDList(obj.getId(), Config.ARTICLERELATESUBJECTWAPXG));
		return util;
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update B_article t set t.deleted = '1' where t.id in (" + ids + ")");
		this.sysLogService.saveObject(Config.LOGTYPESC, this.depict + ids, employee, B_articleServiceImpl.class);
	}
	
	/**
	 * 审核对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateAuditObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		String status = objectMap.get("status").toString();
		objectDao.executeHql("update B_article t set t.auditing = '"+ status +"', t.auditingdate = '" + this.getData() + 
				"', t.auditingempid = '" + employee.getId() + "', t.auditingempname = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
	}
	
	/**
	 * 置顶对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateFirstlyObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		String status = objectMap.get("status").toString();
		objectDao.executeHql("update B_article t set t.firstly = '"+ status +"' where t.id in (" + ids + ")");
	}
	
	/**
	 * 幻灯对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateSlideObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		String status = objectMap.get("status").toString();
		objectDao.executeHql("update B_article t set t.slide = '"+ status +"' where t.id in (" + ids + ")");
	}

	/**
	 * 推荐对象
	 * @param parameters
	 */
	@Override
	public void updateRecommendObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		String status = objectMap.get("status").toString();
		objectDao.executeHql("update B_article t set t.recommend = '"+ status +"' where t.id in (" + ids + ")");
	}
	
	/**
	 * 热门对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateHotObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		String status = objectMap.get("status").toString();
		objectDao.executeHql("update B_article t set t.hot = '"+ status +"' where t.id in (" + ids + ")");
	}
	
	/**
	 * 更改文章类型
	 * @param parameters
	 */
	public void updateObjectType(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String oid = objectMap.get("id").toString();
		String text = objectMap.get("text").toString();
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update B_article t set t.type = '"+ oid + "', t.typename = '"+ text + 
				"' where t.id in (" + ids + ")");
	}
	
	/**
	 * 更改文章栏目
	 * @param parameters
	 */
	public void updateObjectSubject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String oid = objectMap.get("id").toString();
		String text = objectMap.get("text").toString();
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update B_article t set t.subjectid = '"+ oid + "', t.subjectname = '"+ text + 
				"' where t.id in (" + ids + ")");
	}
	
	/**
	 * 恢复对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateObjectDeleted(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update B_article t set t.deleted = '0' where t.id in (" + ids + ")");
	}
	
	/**
	 * 彻底对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void delRealyObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("delete from B_article where id in (" + ids + ")");
		downloadService.delRealyObjectByArticleId(parameters);
	}

	/**
	 * 获得栏目下最后一篇文章
	 */
	public B_article getFinally(String subjectId) throws Exception {
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("subjectid", subjectId));
		c.addOrder(Order.desc("adddate"));
		c.setMaxResults(1);
		List<B_article> list = objectDao.getList(c);
		if(list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}
	
	/**
	 * 每日统计上一日文章的发布总量，并推送数据至微信
	 */
	@SuppressWarnings("unchecked")
	public void saveCountNumPerDay(B_article article) throws Exception {
		String ids = objectDao.get("bb9e3e84a2ed4c59abf5b8329389cc63").getContent().replaceAll("<p>", "").replaceAll("</p>", "");
		
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		calendar.add(Calendar.DAY_OF_YEAR, -1);
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH)+1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		Date date = calendar.getTime();
		String yesterday = format.format(date);
		String sql = "select * from B_article where adddate >= '@#$%000000' and adddate <= '@#$%235959'";
		List<B_article> list = objectDao.queryBySql(sql.replace("@#$%", yesterday));
		
		String id = this.getUUID();
		article.setId(id);
		article.setSubjectid("94516394bb344dc9b8046d5b77453ba1");
		article.setCompanyid("FSDCOMPANY");
		article.setType("wzwz");
		article.setTypename("文章");
		article.setSubjectname("工作日报");
		article.setTitle("工作日报");
		article.setShowtitle(""+ year +"年" + month + "月" + day + "日文章发布总量统计");
		article.setContent("网站于"+ year +"年" + month + "月" + day + "日共发布文章" + list.size() + "篇，望知悉！");
		article.setAdddate(format.format(new Date())+"080000");
		article.setAuditing("true");  //标记已审批
		article.setDeleted("0");
		article.setIspush("1");
		objectDao.save(article);
		
		String[] userIds = ids.split(",");
		for(int i =0; i<userIds.length; i++) {
			A_Employee employee = employeeService.get(userIds[i]);
			if (employee == null) {
				throw new BusinessException("会员用户不存在");
			}
			
			String wechatApiId = sysParamService.getParameterValueByCode(Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			TemplateMessage message = new TemplateMessage();
			message.setItem("first", "尊敬的：" + employee.getRealname(), "#000000");
			message.setItem("keyword1", article.getTitle(), "#000000");
			message.setItem("keyword2", dateFormat.format(new Date()), "#000000");
			message.setItem("remark", "详细内容请点击详情查看，如有疑问，请致电0931-4100411联系我们。", "#1111EE");
			message.setUrl("http://192.168.31.122/fsdsitegroup/gskq/content-" + id + ".htm");
			pushtemplatesService.sendTemplateMessage(wechatApiId, E_pushtemplatesServiceImpl.pushHYcz, employee, message);
		}
	}
	
	/**
	 * 转换文件为SWF文件
	 * @param parameters
	 * @param rootPath
	 * @return
	 * @throws Exception
	 */
	public String zhuanHuanFlash(ParametersUtil parameters, String rootPath) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		String url = objectMap.get("url").toString();
		if(url == null || "".equals(url)){
			throw new BusinessException(depict + "获取缺少URL参数!");
		}
		
		File file = new File(rootPath + url);
		if (!file.exists()) {
			throw new BusinessException(depict + "文件不存在!");
		}
		String prefix = file.getName().substring(file.getName().lastIndexOf(".")+1);
		String[] prefixArray = new String[]{"doc","xls","ppt","pdf"};
		boolean con = false;
		for (String str : prefixArray) {
			if(prefix.equals(str)){
				con = true;
				break;
			}
		}
		if(!con){
			throw new BusinessException(depict + "文件格式不正确!支持格式为：doc、xls、ppt、pdf");
		}
		
		String destFile = "";
		if(!prefix.equals("pdf")){
			destFile = url.substring(0, url.lastIndexOf(".")+1) + "pdf";
			office2PDF(rootPath + url, rootPath + destFile);
		}else{
			destFile = url;
		}
		String swfUrl = url.substring(0, url.lastIndexOf(".")+1) + "swf";
		pdf2SWF(rootPath + destFile, rootPath + swfUrl);
	    System.out.println(swfUrl);
	    return swfUrl;
	}

	/**
	 * Office文件转PDF文件
	 * @param sourceFile
	 * @param destFile
	 * @throws Exception
	 */
	public static void office2PDF(String sourceFile, String destFile) throws Exception{
		File inputFile = new File(sourceFile);
        if (!inputFile.exists()) {
        	throw new BusinessException(depict + "文件不存在!");
        }
            
        // 如果目标路径不存在, 则新建该路径  
        File outputFile = new File(destFile);
        if (!outputFile.getParentFile().exists()) {
        	outputFile.getParentFile().mkdirs();
        }

		// 这里是OpenOffice的安装目录
        String OpenOffice_HOME = "F:\\Program Files (x86)\\OpenOffice 4";
        // 如果从文件中读取的URL地址最后一个字符不是 '\'，则添加'\'
        if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {
        	OpenOffice_HOME += "\\";  
        }
        // 启动OpenOffice的服务  
        String command = OpenOffice_HOME  + "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";  
        Process pro = Runtime.getRuntime().exec(command);  
        // connect to an OpenOffice.org instance running on port 8100  
        OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
        connection.connect();
  
        // convert  
        DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
        converter.convert(inputFile, outputFile);  
            
        // close the connection
        connection.disconnect();
        // 关闭OpenOffice服务的进程
        pro.destroy();
    }

	/**
	 * PDF文件转SWF文件
	 * @param sourceFile
	 * @param destFile
	 * @throws Exception
	 */
	public static void pdf2SWF(String sourceFile, String destFile) throws Exception{
		// 这里是SWFTools的安装目录
		String SWFTOOLS_HOME = "F:\\Program Files (x86)\\SWFTools\\pdf2swf.exe";
        //命令行命令
        String cmd = SWFTOOLS_HOME + " \"" + sourceFile + "\" -o \"" + destFile +"\" -T 9";
		// Runtime执行后返回创建的进程对象
        Process pro = Runtime.getRuntime().exec(cmd);
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(pro.getInputStream())); 
        while (bufferedReader.readLine() != null); 
        pro.waitFor();
	}

	public static void main(String[] args){
		try{
			office2PDF("D:/1.xls", "D:/1.pdf");
			pdf2SWF("D:/1.pdf", "D:/1.swf");
		}catch (Exception e){
			e.printStackTrace();
		}

	}
}



//方法	说明
//Restrictions.eq	等于
//Restrictions.allEq	使用Map，使用key/value进行多个等于的比对
//Restrictions.gt	大于 >
//Restrictions.ge	大于等于 >=
//Restrictions.lt	小于 <
//Restrictions.le	小于等于 < =
//Restrictions.between	对应SQL的BETWEEN子句
//Restrictions.like	对应SQL的LIKE子句
//Restrictions.in	对应SQL的in子句
//Restrictions.and	and关系
//Restrictions.or	or关系
//Restrictions.sqlRestriction	SQL限定查询
